package com.tensquare.web.filter;

import cn.hutool.core.util.StrUtil;
import com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/10/28 10:13
 * 定义网关过滤器
 */
public class MyZuulFilter extends ZuulFilter {
    //定义过滤器类型（详见讲义）
    @Override
    public String filterType() {
        return "pre";
    }
    //定义过滤器的顺序，值越小，执行的越早
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否执行过滤器
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //执行过滤器的业务逻辑,注意：这里即便返回null，也会向下执行
    @Override
    public Object run() throws ZuulException {
        System.out.println("前端的网关过滤器执行。。。");
        //1.得到请求对象
        //1.1)得到当前请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //1.2)得到当前的请求对象
        HttpServletRequest request = currentContext.getRequest();
        //2.得到请求头对象
        String header = request.getHeader("Authorization");
        //3.将我们的请求头放到zuul的请求头上，才能放行（默认，zuul网关不放行其它的请求头）
        if(StrUtil.isNotBlank(header)){
            currentContext.addZuulRequestHeader("Authorization", header);
        }
        return null;
    }
}
